package com.yhc.mq.mq;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.yhc.mq.mq.producer.SendAsyncMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

@Slf4j
@Configuration
public class RocketMQUtil {

    @Autowired
    ProducerBean producer;

    /**
     * 发送普通消息
     *
     * @param content 消息内容
     */
    public void sendMessage(String content, String topic) {
        Message msg = new Message();
        //设置主题和标签
        msg.setTopic(topic);
        msg.setTag("*");
        msg.setBody(content.getBytes());
        try {
            SendResult sendResult = producer.send(msg);
            // 同步发送消息，只要不抛异常就是成功
            if (sendResult != null) {
                log.info(">>>>> 【生产者】系统时间:[{}]同步发送消息成功, MsgID=[{}]", LocalDateTime.now(), sendResult.getMessageId());
            }
        } catch (Exception e) {
            // 消息发送失败
            log.error(">>>>> 【生产者】系统时间:[{}]同步发送消息成功, Topic=[{}]", LocalDateTime.now(), msg.getTopic(), e);
        }
    }

    /**
     * 发送异步消息消息
     *
     * @param content 消息内容
     */
    public void sendAsyncMessage(String content, String topic) {
        Message msg = new Message();
        //设置主题和标签
        msg.setTopic(topic);
        msg.setTag("*");
        msg.setBody(content.getBytes());
        producer.sendAsync(msg, new SendAsyncMessage());
    }

    /**
     * 发送oneWay消息消息
     *
     * @param content 消息内容
     */
    public void sendOneWayMessage(String content, String topic) {
        Message msg = new Message();
        //设置主题和标签
        msg.setTopic(topic);
        msg.setTag("*");
        msg.setBody(content.getBytes());
        producer.sendOneway(msg);
    }
}

